﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using DevTrends.MvcDonutCaching;
using ECG.Common;
using ECG.DAL;
using ECG.Utility;
using ECG.WebUI.CustomHelpers;
using ECG.WebUI.Infrastructure;
using ECG.WebUI.Models;
using System.Linq;

namespace ECG.WebUI.Controllers
{
    public class ProductDetailController : Controller
    {
        //
        // GET: /ProductDetail/

        [DonutOutputCache(Duration = 36000, VaryByParam = "productName;productId")]
        public ActionResult Index(string productName = "", string productId = "")
        {
            ProductDb.UpdateTotalView(productId);
            var model = ProductDb.GetProductById(productId) ?? new ViewProductDetailDto();

            // Add domain babo.vn into attribute src of img tag
            MatchCollection mc;
            var r = new Regex(@"(?<=img[^>]*?src\=[\x27\x22])(?<Url>[^\x27\x22]*)(?=[\x27\x22][^>]*?)");
            var hostForImage = ConfigurationManager.AppSettings["HostContainImages"];
            mc = r.Matches(model.Description);
            if (mc.Count > 0)
            {
                foreach (var item in mc)
                {
                    if (item == null || item.ToString().Contains("http")) continue;
                    if (!model.Description.Contains(hostForImage + item))
                    {
                        model.Description = model.Description.Replace(item.ToString(), hostForImage + item);
                    }
                }
            }

            ViewBag.SizeList = ProductSizeDb.GetAllByProductId(productId) ?? new List<ProductSizeListByPidDto>();
            ViewBag.ColorList = ProductImageDb.GetImageHasColorInfo(productId) ?? new List<ProductImageHasColorInfoDto>();
            ViewBag.CateId = model.CategoryId;

            return View(model);
        }

        /// <summary>
        /// Check cart null, login null, calculate total money, redirect to order
        /// </summary>
        /// <param name="pInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(ProductOrderInfo pInfo)
        {
            // Create session order
            if (Session[SessionConfig.SessionCartInfor] == null)
            {
                var cartInfor = new OrderInfo { ProductOrderList = new List<ProductOrderInfo> { pInfo } };
                cartInfor.TotalMoney = pInfo.PromotionPrice > 0 ? pInfo.PromotionPrice * pInfo.ProductQuantity : pInfo.RootPriceProduct * pInfo.ProductQuantity;
                Session[SessionConfig.SessionCartInfor] = cartInfor;
            }
            else
            {
                var cartInfor = (OrderInfo)Session[SessionConfig.SessionCartInfor];
                cartInfor = FunctionHelpers.CalTotalOrder(cartInfor, pInfo);
                Session[SessionConfig.SessionCartInfor] = cartInfor;
            }

            // Check login
            return RedirectToAction(Session[SessionConfig.SessionCustomerLogin] == null ? "Index" : "Finish", "Order");
        }

        public PartialViewResult ProductImageDetail(string productId = "")
        {
            var model = ProductImageDb.GetImageHasColorInfo(productId) ?? new List<ProductImageHasColorInfoDto>();
            return PartialView(model);
        }

        public PartialViewResult ProductImageByColorDetail(string productId = "", string ColorId = "")
        {
            var model = ProductImageDb.GetImageByColorId(productId, ColorId) ?? new List<ProductImageHasColorInfoDto>();
            return PartialView(model);
        }

        [DonutOutputCache(CacheProfile = "OneDay")]
        public PartialViewResult ProductConcern(string categoryId = "", string ProductDate = "", string ProductId = "")
        {

            var model = ProductDb.GetTopProductConcern(categoryId, ProductDate, ProductId) ?? new List<ProductByCateTopListPagingDto>();
            //neu so luong san pham cung nhom thap hon 3 thi lay lai 3 san pham dau tien
            //cu the tao thanh vong trong khep kin - rat co loi cho con robot cua google index san pham tot hon
            if (model.Count < 3)
            {
                var modelTem = ProductDb.GetTopProductConcern_more(categoryId, ProductId) ?? new List<ProductByCateTopListPagingDto>();
                if (modelTem.Count > 0)
                {
                    foreach (var productByCateTopListPagingDto in modelTem)
                    {
                        var item = model.Where(m => m.Id == productByCateTopListPagingDto.Id).FirstOrDefault();
                        if (item != null) continue;
                        model.Add(productByCateTopListPagingDto);
                    }
                }
            }
            var itemCate = ProductCategoryDb.GetById(categoryId) ?? new ProductCategoryDto();
            ViewBag.CateName = itemCate.Name;
            ViewBag.CateId = categoryId;
            return PartialView(model);
        }

        public PartialViewResult ProductViewedHistory(List<ProductViewHistoryModel> data)
        {
            var model = data ?? new List<ProductViewHistoryModel>();
            return PartialView(model);
        }

        [DonutOutputCache(CacheProfile = "OneDay")]
        public PartialViewResult TagsByProduct(string productId)
        {
            var model = ProductTagDb.GetProductTagByProductId(productId) ?? new List<ProductTagDto>();
            return PartialView(model);
        }
        [DonutOutputCache(CacheProfile = "OneDay")]
        public PartialViewResult ProductRate(string productId)
        {
            ViewBag.productId = productId;
            var dataCusRate = RateDb.GetCustomerRate(productId) ?? new RateDetailDto
                                                                     {
                                                                         Star1 = 0,
                                                                         Star2 = 0,
                                                                         Star3 = 0,
                                                                         Star4 = 0,
                                                                         Star5 = 0,
                                                                         TotalRate = 0,
                                                                         AverageRate = 0
                                                                     };
            return PartialView(dataCusRate);
        }
        [DonutOutputCache(CacheProfile = "OneDay")]
        public PartialViewResult ProductComment(string productId)
        {
            ViewBag.productId = productId;
            return PartialView();
        }
        public PartialViewResult ProductCommentPagging(string productId, int page = 1, int sort = 0)
        {
            ViewBag.productId = productId;
            var itemsPerPage = 6;
            var totalPage = 0;
            var model = ProductCommentDb.GetProductCommentByProductIdPagging(page, itemsPerPage, ref totalPage, productId, sort) ?? new List<ProductCommentListDetailDto>();
            ViewBag.TotalPage = totalPage;
            ViewBag.CurrentPage = page;
            ViewBag.Sort = sort;
            return PartialView(model);
        }
        public PartialViewResult CustomerBought(string productId)
        {
            var model = ProductTogetherDb.GetProductTogetherByProductId(productId);
            return PartialView(model);
        }

        //productIdHis: la productId cua san pham moi ma khac hang vua xem
        [DonutOutputCache(CacheProfile = "OneDay")]
        public PartialViewResult ProductDetailRight(string productIdHis, int page = 1)
        {
            var itemsPerPage = 3;
            var totalPage = 0;
            var model = ProductDb.GetProductSPquantam_productDetail(page, itemsPerPage, ref totalPage, productIdHis) ?? new List<ProductRateByCateTopListPagingDto>();
            ViewBag.CurrentPage = page;
            ViewBag.TotalPage = totalPage;
            ViewBag.productIdHis = productIdHis;
            return PartialView(model);
        }

        public PartialViewResult ProductDetailRight_spquantamPagging(string productIdHis, int page = 1)
        {
            var itemsPerPage = 3;
            var totalPage = 0;
            var model = ProductDb.GetProductSPquantam_productDetail(page, itemsPerPage, ref totalPage, productIdHis) ?? new List<ProductRateByCateTopListPagingDto>();
            ViewBag.CurrentPage = page;
            ViewBag.TotalPage = totalPage;
            return PartialView(model);
        }

        public JsonResult RegCommentFast(string FullName = "", string Email = "", int rate = 1, string pId = "")
        {
            var cusSession = Session[SessionConfig.SessionCustomerLogin] as CustomerInfo;
            var cusId = string.Empty;
            if (cusSession != null)
            {
                cusId = cusSession.CustomerId;
            }
            else
            {
                var hasEmail = CustomerDb.GetByEmail(Email);
                if (hasEmail == null)
                {
                    var passslat = Guid.NewGuid().ToString();
                    var customerInfo = new CustomerDto()
                                           {
                                               Id = FunctionHelpers.GenerateId(),
                                               Password = "123456".CreatePasswordHash(passslat),
                                               PasswordSalt = passslat,
                                               Email = Email,
                                               FullName = FullName
                                           };
                    CustomerDb.Add(customerInfo);
                    cusId = customerInfo.Id;
                }
                else
                {
                    cusId = hasEmail.Id;
                }
            }

            if (!string.IsNullOrEmpty(cusId))
            {
                //Cap nhap hoac them moi rate
                var listRate = RateDb.GetCusAndProductId(cusId, pId);
                if (listRate != null)
                {
                    //cap nhap
                    listRate.Star = rate;
                    RateDb.Update(listRate);
                }
                else
                {
                    //them moi rate
                    var newRate = new RateDto()
                    {
                        CustomerId = cusId,
                        ProductId = pId,
                        Star = rate
                    };
                    RateDb.Add(newRate);
                }
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        public JsonResult addComment(string txtCommentTitle = "", string txtComment = "", string txtAccountNameComment = "", string pId = "")
        {
            var cusSession = Session[SessionConfig.SessionCustomerLogin] as CustomerInfo;

            if (!CommonHelpers.CheckExistLogin() || cusSession == null)
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }

            if (!string.IsNullOrEmpty(txtCommentTitle) && !string.IsNullOrEmpty(txtComment) && !string.IsNullOrEmpty(pId))
            {
                var modelComment = new ProductCommentDto
                                       {
                                           ProductId = pId,
                                           Title = txtCommentTitle,
                                           Content = txtComment,
                                           CustomerId = cusSession.CustomerId,
                                           ParentId = 0,
                                           CreateDate = DateTime.Now,
                                           UpdateDate = DateTime.Now,
                                           Agree = false,
                                           Active = true
                                       };
                ProductCommentDb.Add(modelComment);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }
}
